/**
 * @Author: wangjian 656876071@qq.com
 * @Date: 2024-07-18 21:10:13
 * @LastEditors: wangjian 656876071@qq.com
 * @LastEditTime: 2024-07-29 22:35:47
 * @FilePath: src/views/auth/LoginHooks.ts
 * @Description: 登录页脚本
 */
import {onMounted, ref} from 'vue'
import {useRouter} from "vue-router";
import {message} from 'ant-design-vue'
import {TOKEN_KEY} from '@/core/utils/request'

import axios from 'axios'

export default () => {
    onMounted(() => {
        console.log('login mounted')
        const token: string | null = localStorage.getItem(TOKEN_KEY)
        if (!token) {
            console.log("无token，请登录")
            return
        }
        message.success('已登录，正在跳转...')
        forward()
    })

    /**
     * 路由相关
     */
    const router = useRouter()
    const forward = () => router.push('/')

    /**
     * 登录
     */
    const username = ref('')
    const password = ref('')
    const login = () => {
        // 模拟后端认证
        type AuthData = {
            username: string,
            password: string
        }
        const authData: AuthData = {
            username: username.value,
            password: password.value
        }
        axios.post('/api/login', authData).then(res => {
            console.log(res)
            if (res.data.code == 0) {
                console.log('认证成功', res.data)
                localStorage.setItem(TOKEN_KEY, res.data.data)
                message.success('认证成功')
                forward()
            } else {
                message.error('认证不通过，请检查！')
            }
        }).catch(err => {
            console.log(err)
        })

    }


    return {
        username,
        password,
        login
    }
}
